package com.bac.rentmap.ad.crawler.random;

import java.io.IOException;
import java.util.List;
import java.util.Random;

import com.bac.rentmap.ad.crawler.AdCrawler;
import com.bac.rentmap.ad.crawler.Context;
import com.bac.rentmap.ad.crawler.CrawledAd;

public class RandomPageAdCrawler<T extends CrawledAd> implements AdCrawler<T> {
	private AdCrawler<T> adCrawler;
	private Random random = new Random();

	public RandomPageAdCrawler(AdCrawler<T> adCrawler) {
		this.adCrawler = adCrawler;
	}

	public List<T> crawl(Context context) throws IOException {
		if (context.getPage() == null) {
			try {
				context = (Context) context.clone();
				context.setPage((int) Math.abs(10 * random.nextGaussian()));
			} catch (CloneNotSupportedException e) {
				throw new IllegalArgumentException("Can't crawl ads", e);
			}
		}
		return adCrawler.crawl(context);
	}

}
